<?php
/**
 * 统计基础方法
 * User: cxm
 * Date: 2018/12/3
 * Time: 9:33
 */

namespace App\Http\Controllers\Admin\Count;

use App\Http\Controllers\Admin\Controller;
use DB, Config, Validator;

class StatisticsController extends Controller
{
    /**
     * 默认显示的天数 (时间类型为日)
     **/
    private $day_len = 14;
    /**
     * 默认显示的月数 (时间类型为月)
     **/
    private $month_len = 12;
    /**
     * 默认显示年数 (时间类型为年)
     **/
    private $year_len = 10;
    /**
     * 默认显示季度数
     * @var array
     */
    private $quarter_len = 30;

    /**
     * 用户数量统计
     * @param string $datemin 开始时间
     * @param string $datemax 结束时间
     * @param string $time_type 时间类型 (year年|month月|day日)
     * @return object data:数据信息
     */
    public function selectUser($datemin, $datemax, $time_type)
    {
        // 判断查询类型
        if ($time_type == 'days') {
            $max_date = $datemax ? $datemax : date('Y-m-d');
            $min_date = $datemin ? $datemin : date('Y-m-d', strtotime($max_date . ' -' . $this->day_len . ' days'));
            $format   = '%Y-%m-%d';
        } else if ($time_type == 'month') {
            $max_date = $datemax ? $datemax : date('Y-m');
            $min_date = $datemin ? $datemin : date('Y-m', strtotime($max_date . ' -' . $this->month_len . ' month'));
            $format   = '%Y-%m';
        } else{
            $max_date = $datemax ? $datemax : date('Y');
            $min_date = $datemin ? $datemin : date('Y', strtotime($max_date . ' -' . $this->year_len . ' year'));
            $format   = '%Y';
        }

        $table_prefix = DB::getTablePrefix();

        $data = DB::table('users')->selectRaw("count(distinct {$table_prefix}users.id) as total,
            DATE_FORMAT({$table_prefix}users.created_at,'" . $format . "') as create_day"
        );

        if ($time_type == 'days') {
            $data = $data->whereBetween('created_at', [$min_date, $max_date]);
        } else if ($time_type == 'month') {
            $data = $data->where(function ($query) use ($min_date, $max_date) {
                $query->whereDate('created_at', '>=', $min_date)
                    ->whereDate('created_at', '<=', $max_date)
                    ->orwhere('created_at', 'like', '%' . $max_date . '%');
            });
        } else {
            $data = $data->whereYear('created_at', '>=', $min_date)
                ->whereYear('created_at', '<=', $max_date);
        }

        $data = $data->whereNull('deleted_at')
            ->groupBy('create_day')
            ->orderBy('create_day', 'asc')
            ->get();
        $res  = array();
        foreach ($data as $v) {
            $res[$v->create_day] = $v->total;
        }
        return $res;
    }

    /**
     * 固定获取用户中奖、领取数量统计
     * @param int $activity_id 活动ID
     * @param string $datemin 开始时间
     * @param string $datemax 结束时间
     * @param string $time_type 时间类型 (year年|month月|day日)
     * @param int $type  1 中奖数量 2领取数量
     * @return object data:数据信息
     */
    public function selectUserPrize($activity_id,$datemin, $datemax, $time_type,$type=1){
        // 判断查询类型
        if ($time_type == 'days') {
            $max_date = $datemax ? $datemax : date('Y-m-d');
            $min_date = $datemin ? $datemin : date('Y-m-d', strtotime($max_date . ' -' . $this->day_len . ' days'));
            $format   = '%Y-%m-%d';
        } else if ($time_type == 'month') {
            $max_date = $datemax ? $datemax : date('Y-m');
            $min_date = $datemin ? $datemin : date('Y-m', strtotime($max_date . ' -' . $this->month_len . ' month'));
            $format   = '%Y-%m';
        } else{
            $max_date = $datemax ? $datemax : date('Y');
            $min_date = $datemin ? $datemin : date('Y', strtotime($max_date . ' -' . $this->year_len . ' year'));
            $format   = '%Y';
        }
        $table_prefix = DB::getTablePrefix();
        $data = DB::table('award_history')
            ->where('activity_id',$activity_id)// 指定活动
            ->selectRaw( "
                count(distinct {$table_prefix}award_history.id) as total,
                DATE_FORMAT({$table_prefix}award_history.created_at,'" . $format . "') as create_day"
            );

        if ($type == 2) { // 领取情况
            $data = $data->where('status',1); // 已兑奖
        }

        if ($time_type == 'days') {
            $data = $data->whereBetween('created_at', [$min_date, $max_date]);
        } else if ($time_type == 'month') {
            $data = $data->where(function ($query) use ($min_date, $max_date) {
                $query->whereDate('created_at', '>=', $min_date)
                    ->whereDate('created_at', '<=', $max_date)
                    ->orwhere('created_at', 'like', '%' . $max_date . '%');
            });
        } else {
            $data = $data->whereYear('created_at', '>=', $min_date)
                ->whereYear('created_at', '<=', $max_date);
        }

        $data = $data->whereNull('deleted_at')
            ->groupBy('create_day')
            ->orderBy('create_day', 'asc')
            ->get();
        $res  = array();
        foreach ($data as $v) {
            $res[$v->create_day] = $v->total;
        }
        return $res;
    }

    /**
     * 固定获取用户中奖、领取数量统计
     * @param int $award_id 奖项ID
     * @param string $datemin 开始时间
     * @param string $datemax 结束时间
     * @param string $time_type 时间类型 (year年|month月|day日)
     * @param int $type  1 中奖数量 2领取数量
     * @return object data:数据信息
     */
    public function selectUserAwards($award_id,$datemin, $datemax, $time_type,$type=1){
        // 判断查询类型
        if ($time_type == 'days') {
            $max_date = $datemax ? $datemax : date('Y-m-d');
            $min_date = $datemin ? $datemin : date('Y-m-d', strtotime($max_date . ' -' . $this->day_len . ' days'));
            $format   = '%Y-%m-%d';
        } else if ($time_type == 'month') {
            $max_date = $datemax ? $datemax : date('Y-m');
            $min_date = $datemin ? $datemin : date('Y-m', strtotime($max_date . ' -' . $this->month_len . ' month'));
            $format   = '%Y-%m';
        } else{
            $max_date = $datemax ? $datemax : date('Y');
            $min_date = $datemin ? $datemin : date('Y', strtotime($max_date . ' -' . $this->year_len . ' year'));
            $format   = '%Y';
        }
        $table_prefix = DB::getTablePrefix();
        $data = DB::table('award_history')
            ->where('award_id',$award_id)// 指定活动
            ->selectRaw( "
                count(distinct {$table_prefix}award_history.id) as total,
                DATE_FORMAT({$table_prefix}award_history.created_at,'" . $format . "') as create_day"
            );

        if ($type == 2) { // 领取情况
            $data = $data->where('status',1); // 已兑奖
        }

        if ($time_type == 'days') {
            $data = $data->whereBetween('created_at', [$min_date, $max_date]);
        } else if ($time_type == 'month') {
            $data = $data->where(function ($query) use ($min_date, $max_date) {
                $query->whereDate('created_at', '>=', $min_date)
                    ->whereDate('created_at', '<=', $max_date)
                    ->orwhere('created_at', 'like', '%' . $max_date . '%');
            });
        } else {
            $data = $data->whereYear('created_at', '>=', $min_date)
                ->whereYear('created_at', '<=', $max_date);
        }

        $data = $data->whereNull('deleted_at')
            ->groupBy('create_day')
            ->orderBy('create_day', 'asc')
            ->get();
        $res  = array();
        foreach ($data as $v) {
            $res[$v->create_day] = $v->total;
        }
        return $res;
    }

    /**
     * 用户参与情况统计
     * @param $datemin 开始时间
     * @param $datemax 结束时间
     * @param $time_type 时间类型 (year年|month月|day日)
     * @param $search_type total 总步数| num 总人数
     * @return mixed
     */
    public function selectUserJoin($datemin, $datemax, $time_type,$search_type){
        // 判断查询类型
        if ($time_type == 'days') {
            $max_date = $datemax ? $datemax : date('Y-m-d').' 23:59:59';
            $min_date = $datemin ? $datemin : date('Y-m-d', strtotime($max_date . ' -' . $this->day_len . ' days')).' 00:00:00';
            $format   = '%Y-%m-%d';
        } else if ($time_type == 'month') {
            $max_date = $datemax ? $datemax : date('Y-m');
            $min_date = $datemin ? $datemin : date('Y-m', strtotime($max_date . ' -' . $this->month_len . ' month'));
            $format   = '%Y-%m';
        } else{
            $max_date = $datemax ? $datemax : date('Y');
            $min_date = $datemin ? $datemin : date('Y', strtotime($max_date . ' -' . $this->year_len . ' year'));
            $format   = '%Y';
        }

        $table_prefix = DB::getTablePrefix();

        $data = DB::table('user_step_record');
        if ($search_type == 'num') {
            $data->selectRaw("
                count(distinct {$table_prefix}user_step_record.user_id) as total,
                DATE_FORMAT({$table_prefix}user_step_record.date,'" . $format . "') as create_day"
            );
        } else {
            $data->selectRaw("
                sum(distinct {$table_prefix}user_step_record.steps) as total,
                DATE_FORMAT({$table_prefix}user_step_record.date,'" . $format . "') as create_day"
            );
        }

        if ($time_type == 'days') {
            $data = $data->whereBetween('date', [$min_date, $max_date]);
        } else if ($time_type == 'month') {
            $data = $data->where(function ($query) use ($min_date, $max_date) {
                $query->whereDate('date', '>=', $min_date)
                    ->whereDate('date', '<=', $max_date)
                    ->orwhere('date', 'like', '%' . $max_date . '%');
            });
        } else {
            $data = $data->whereYear('date', '>=', $min_date)
                ->whereYear('date', '<=', $max_date);
        }

        $data = $data->whereNull('deleted_at')
            ->groupBy('create_day')
            ->orderBy('create_day', 'asc')
            ->get();
        $res  = array();
        foreach ($data as $v) {
            $res[$v->create_day] = $v->total;
        }
        return $res;
    }

    /**
     * 查询指定时间范围内的所有日期，月份，季度，年份
     * @param $startDate   指定开始时间，Y-m-d格式
     * @param $endDate     指定结束时间，Y-m-d格式
     * @param $type        类型，days 天，month 月份，quarter 季度，year 年份
     * @return array
     */
    public function getDateByInterval($startDate, $endDate, $type){
        $endDate = $endDate ? $endDate :date('Y-m-d');
        if ($type == 'days') {
            $startDate = $startDate ? $startDate : date('Y-m-d', strtotime($endDate . ' -' . $this->day_len . ' days' ));
        }else if ($type == 'month') {
            $startDate = $startDate ? $startDate : date('Y-m-d', strtotime($endDate . ' -' . $this->month_len . ' month'));
        }else if($type == 'quarter'){
            $startDate = $startDate ? $startDate : date('Y-m-d', strtotime($endDate . ' -1 year'));
        }else{
            $startDate = $startDate ? $startDate : date('Y-m-d', strtotime($endDate . ' -' . $this->month_len . ' year' ));
        }
        if (date('Y-m-d', strtotime($startDate)) != $startDate || date('Y-m-d', strtotime($endDate)) != $endDate) {
            return ['code'=>200,'msg'=>'日期格式不正确'];
        }
        $tempDate = $startDate;
        $returnData = [];
        $i = 0;
        if ($type == 'days') {    // 查询所有日期
            while (strtotime($tempDate) < strtotime($endDate)) {
                if ($i > $this->day_len) {
                    break;
                }
                $tempDate = date('Y-m-d', strtotime('+' . $i . ' day', strtotime($startDate)));
                $temp['name'] = $tempDate;
                $returnData[] = $temp;
                $i++;
            }
        } elseif ($type == 'month') {    // 查询所有月份以及开始结束时间
            while (strtotime($tempDate) < strtotime($endDate)) {
                if ($i > $this->month_len) {
                    break;
                }
                $temp = [];
                $month = strtotime('first day of +' . $i . ' month', strtotime($startDate));
                $temp['name'] = date('Y-m', $month);
                $temp['startDate'] = date('Y-m-01', $month);
                $temp['endDate'] = date('Y-m-t', $month);
                $tempDate = $temp['endDate'];
                $returnData[] = $temp;
                $i++;
            }
        } elseif ($type == 'quarter') {    // 查询所有季度以及开始结束时间
            while (strtotime($tempDate) < strtotime($endDate)) {
                if ($i > $this->quarter_len) {
                    break;
                }
                $temp = [];
                $quarter = strtotime('first day of +' . $i . ' month', strtotime($startDate));
                $q = ceil(date('n', $quarter) / 3);
                $temp['name'] = date('Y', $quarter) . '第' . $q . '季度';
                $temp['startDate'] = date('Y-m-01', mktime(0, 0, 0, $q * 3 - 3 + 1, 1, date('Y', $quarter)));
                $temp['endDate'] = date('Y-m-t', mktime(23, 59, 59, $q * 3, 1, date('Y', $quarter)));
                $tempDate = $temp['endDate'];
                $returnData[] = $temp;
                $i = $i + 3;
            }
        } elseif ($type == 'year') {    // 查询所有年份以及开始结束时间
            while (strtotime($tempDate) < strtotime($endDate)) {
                if ($i > $this->year_len) {
                    break;
                }
                $temp = [];
                $year = strtotime('+' . $i . ' year', strtotime($startDate));
                $temp['name'] = date('Y', $year) . '年';
                $temp['name_str'] = date('Y', $year);
                $temp['startDate'] = date('Y-01-01', $year);
                $temp['endDate'] = date('Y-12-31', $year);
                $tempDate = $temp['endDate'];
                $returnData[] = $temp;
                $i++;
            }
        }
        return $returnData;
    }
}
